package com.qingcheng.service.impl;
import com.alibaba.dubbo.config.annotation.Service;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.qingcheng.dao.OrderConfigMapper;
import com.qingcheng.dao.OrderItemMapper;
import com.qingcheng.dao.OrderLogMapper;
import com.qingcheng.dao.OrderMapper;
import com.qingcheng.entity.PageResult;
import com.qingcheng.pojo.order.*;
import com.qingcheng.service.order.OrderService;
import com.qingcheng.util.IdWorker;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Map;

@Service(interfaceClass =OrderService.class )
public class OrderServiceImpl implements OrderService {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private OrderLogMapper orderLogMapper;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private OrderConfigMapper orderConfigMapper;

    /**
     * 定义订单超时的方法
     */
    @Override
    @Transactional
    public void closeOrder() {
        //获取系统超时时间配置
        OrderConfig orderConfig = orderConfigMapper.selectByPrimaryKey(1);
        Integer orderTimeout = orderConfig.getOrderTimeout();
        //计算当前时间与超时时间的结果
        LocalDateTime localDateTime=LocalDateTime.now().minusDays(orderTimeout);
        //按条件查询到需要关闭的订单集合，paytime<计算时间  orderSatus=0 未付款  isDelete=0 未删除
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andLessThan("createTime",localDateTime); //订单时间超过计算时间
        criteria.andEqualTo("orderStatus","0");  //未付款
        criteria.andEqualTo("isDelete","0"); //未删除
        List<Order> orders = orderMapper.selectByExample(example);
        //遍历集合，将订单状态改为关闭 orderstatus=4
        if(orders!=null && orders.size()!=0){
            for (Order order : orders) {
                order.setOrderStatus("4");  //状态修改为已关闭
                order.setCloseTime(new Date()); //设置关闭时间
                //存入数据库
                orderMapper.updateByPrimaryKeySelective(order);
                //增加日志信息
                OrderLog orderLog=new OrderLog();
                //雪花算法生成Id
                orderLog.setId(idWorker.nextId()+"");
                orderLog.setOperater("admin");
                orderLog.setOperateTime(new Date());
                orderLog.setOrderId(order.getId());
                orderLog.setOrderStatus("4");
                orderLog.setPayStatus("0");
                orderLog.setConsignStatus("0");
                orderLog.setRemarks("规定时间未支付，订单超时");
                //保存日志
                orderLogMapper.insert(orderLog);
            }
        }
    }

    /**
     * 定义拆分订单的方法
     * @param splitParams  [ splitParma{orderId:1 ,orderItemId:2 ,num:20},splitParma{orderId:1 ,orderItemId:3 ,num:10} ]
     */
    public void splitOrder(SplitParam[] splitParams){
        //获取主表信息
        String orderId = splitParams[0].getOrderId();
        Order order = orderMapper.selectByPrimaryKey(orderId);
        //生成新的order作为新的订单
        Order newOrder=new Order();
        BeanUtils.copyProperties(order,newOrder);  //spring自带工具类，copy一个对象，地址值改变
        //设置新对象id
        String newId=idWorker.nextId()+"";
        newOrder.setId(newId);
        //设置新旧表数量
        newOrder.setTotalNum(order.getTotalNum()/2);
        order.setTotalNum(order.getTotalNum()-newOrder.getTotalNum());
        //设置新表金额（偷懒下，直接除以2）
        newOrder.setPayMoney(order.getPayMoney()/2);
        order.setPayMoney(order.getPayMoney()/2);
        //设置新旧表实付金额
        newOrder.setTotalMoney(newOrder.getTotalMoney()/2);
        order.setTotalMoney(order.getTotalMoney()/2);
        //新表存入，旧更新
        orderMapper.insert(newOrder);
        orderMapper.updateByPrimaryKeySelective(order);
        //遍历循环，查询从表信息
        for (SplitParam splitParam : splitParams) {
            //获取从表id
            String orderItemId = splitParam.getOrderItemId();
            //查询从表
            OrderItem orderItem = orderItemMapper.selectByPrimaryKey(orderItemId);
            if(splitParam.getNum()>orderItem.getNum()){
                throw new RuntimeException("拆分数量不得大于购买商品数量");
            }
            OrderItem newOrderItem=new OrderItem();
            BeanUtils.copyProperties(orderItem,newOrderItem);
            newOrderItem.setId(idWorker.nextId()+"");
            //设置新旧从表数量
            newOrderItem.setNum(splitParam.getNum()); //数量为原有数量减去拆分数量
            orderItem.setNum(orderItem.getNum()-splitParam.getNum()); //数量为拆分数量
            //设置新旧从表总金额
            newOrderItem.setMoney(orderItem.getPrice()*newOrderItem.getNum()); //总金额为现有数量*单价
            orderItem.setMoney(orderItem.getNum()*orderItem.getPrice());
            //设置新旧表实际金额
            newOrderItem.setPayMoney(newOrderItem.getMoney()+newOrderItem.getPostFee()); //总金额+运费
            orderItem.setPayMoney(orderItem.getMoney()+orderItem.getPostFee());
            //设置新表orderId
            newOrderItem.setOrderId(newId);
            //新增新建从表
            orderItemMapper.insert(newOrderItem);
            //更新已有从表
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }
        OrderLog orderLog1=new OrderLog();
        //雪花算法生成Id
        orderLog1.setId(idWorker.nextId()+"");
        orderLog1.setOperater("admin");
        orderLog1.setOperateTime(new Date());
        orderLog1.setOrderId(order.getId());
        orderLog1.setOrderStatus(order.getOrderStatus());
        orderLog1.setPayStatus(order.getPayStatus());
        orderLog1.setConsignStatus(order.getConsignStatus());
        orderLog1.setRemarks("订单拆分后原订单");
        orderLogMapper.insert(orderLog1);

        OrderLog orderLog2=new OrderLog();
        //雪花算法生成Id
        orderLog2.setId(idWorker.nextId()+"");
        orderLog2.setOperater("admin");
        orderLog2.setOperateTime(new Date());
        orderLog2.setOrderId(newOrder.getId());
        orderLog2.setOrderStatus(newOrder.getOrderStatus());
        orderLog2.setPayStatus(newOrder.getPayStatus());
        orderLog2.setConsignStatus(newOrder.getConsignStatus());
        orderLog2.setRemarks("订单拆分后新订单");
        orderLogMapper.insert(orderLog2);
    }

    /**
     * 定义合并的方法
     * @param orderId1
     * @param orderId2
     */
    @Override
    @Transactional
    public void mergeOrder(String orderId1, String orderId2) {
        //获取主表对象
        Order order1 = orderMapper.selectByPrimaryKey(orderId1);
        //获取从表对象
        Order order2 = orderMapper.selectByPrimaryKey(orderId2);
        if(order1==null || order2==null){
            throw new RuntimeException("您输入的单号有误");
        }
        if( !order1.getReceiverAddress().equals(order2.getReceiverAddress())){
            throw new RuntimeException("不能是同一订单");
        }
        if(orderId1==orderId2 ){
            throw new RuntimeException("两个订单不能相同");
        }
        //将从表金额和主表金额合计、数量合计、实际支付、优惠金额后赋值给主表
        //金额合并
        order1.setTotalMoney(order1.getTotalMoney()+order2.getTotalMoney());
        //数量合并
        order1.setTotalNum(order1.getTotalNum()+order2.getTotalNum());
        //优惠合并
        order1.setPreMoney(order1.getPayMoney()+order2.getPreMoney());
        //实付金额合并
        order1.setPayMoney(order1.getPayMoney()+order2.getPayMoney());
        //保存主表信息
        orderMapper.updateByPrimaryKeySelective(order1);
        //删除从表信息
        order2.setIsDelete("1");
        orderMapper.updateByPrimaryKeySelective(order2);

        //子表的修改
        //将子表orderId改为orderId1
        //将字表运费置零
        Example example=new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",orderId2);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        for (OrderItem orderItem : orderItemList) {
            orderItem.setId(idWorker.nextId()+"");
            orderItem.setPostFee(0);
            orderItem.setOrderId(orderId1);
            orderItemMapper.updateByPrimaryKeySelective(orderItem);
        }


        //修改日志信息
        OrderLog orderLog1=new OrderLog();
        //雪花算法生成Id
        orderLog1.setId(idWorker.nextId()+"");
        orderLog1.setOperater("admin");
        orderLog1.setOperateTime(new Date());
        orderLog1.setOrderId(order1.getId());
        orderLog1.setOrderStatus(order1.getOrderStatus());
        orderLog1.setPayStatus(order1.getPayStatus());
        orderLog1.setConsignStatus(order1.getConsignStatus());
        orderLog1.setRemarks("订单合并");
        //保存日志
        orderLogMapper.insert(orderLog1);


        //修改日志信息
        OrderLog orderLog2=new OrderLog();
        //雪花算法生成Id
        orderLog2.setId(idWorker.nextId()+"");
        orderLog2.setOperater("admin");
        orderLog2.setOperateTime(new Date());
        orderLog2.setOrderId(order2.getId());
        orderLog2.setOrderStatus(order2.getOrderStatus());
        orderLog2.setPayStatus(order2.getPayStatus());
        orderLog2.setConsignStatus(order2.getConsignStatus());
        orderLog2.setRemarks("订单删除");
        //保存日志
        orderLogMapper.insert(orderLog2);
    }

    /**
     * 定义修改方法
     * @param  orders
     */
    @Override
    @Transactional
    public void batchSend(Order[] orders) {
        //判断存入的表单中的发货状态
        for (Order order : orders) {
            if(order.getShippingName()==null || order.getShippingCode()==null){
                throw new RuntimeException("请填写完整的物流信息");
            }
        }
        //存入日志信息，同时保存到数据库
        //创建日志对象
        OrderLog orderLog=new OrderLog();
        for (Order order : orders) {
            //雪花算法生成Id
            orderLog.setId(idWorker.nextId()+"");
            orderLog.setOperater("admin");
            orderLog.setOperateTime(new Date());
            orderLog.setOrderId(order.getId());
            orderLog.setOrderStatus("2");
            orderLog.setPayStatus("1");
            orderLog.setConsignStatus("1");
            //保存日志
            orderLogMapper.insert(orderLog);
            //保存订单信息
            order.setConsignTime(new Date());
            order.setOrderStatus("2");
            order.setConsignStatus("1");
            orderMapper.updateByPrimaryKeySelective(order);
        }


    }




    /**
     * 定义查询未发货订单列表
     * @param ids
     * @return
     */
    @Override
    @Transactional
    public List<Order> findOrderUnconsign(String[] ids) {
        //增加健壮性判断
        if(ids==null || ids.length==0){
            throw new RuntimeException("请选择未发货的订单");
        }
        Example example=new Example(Order.class);
        //增加查询条件
        Example.Criteria criteria = example.createCriteria();
        //sql语句： select * from tb_order where id in [1,2,3,5] and consignStatus=0
        criteria.andIn("id", Arrays.asList(ids));
        criteria.andEqualTo("consignStatus","0");
        //查询列表
        return orderMapper.selectByExample(example);
    }


    /**
     * 定义根据id查询订单完整信息的方法
     * @param id
     * @return
     */
    @Override
    @Transactional
    public WholeOrder findWholeOrder(String id){
        //根据id查询主表order
        Order order = orderMapper.selectByPrimaryKey(id);
        //根据id查询从表的集合
        Example example=new Example(OrderItem.class);
        Example.Criteria criteria = example.createCriteria();
        criteria.andEqualTo("orderId",id);
        List<OrderItem> orderItemList = orderItemMapper.selectByExample(example);
        WholeOrder wholeOrder=new WholeOrder();
        wholeOrder.setOrder(order);
        wholeOrder.setOrderItemsList(orderItemList);
        return wholeOrder;
    }



    /**
     * 返回全部记录
     * @return
     */
    public List<Order> findAll() {
        return orderMapper.selectAll();
    }

    /**
     * 分页查询
     * @param page 页码
     * @param size 每页记录数
     * @return 分页结果
     */
    public PageResult<Order> findPage(int page, int size) {
        PageHelper.startPage(page,size);
        Page<Order> orders = (Page<Order>) orderMapper.selectAll();
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 条件查询
     * @param searchMap 查询条件
     * @return
     */
    public List<Order> findList(Map<String, Object> searchMap) {
        Example example = createExample(searchMap);
        return orderMapper.selectByExample(example);
    }

    /**
     * 分页+条件查询
     * @param searchMap
     * @param page
     * @param size
     * @return
     */
    public PageResult<Order> findPage(Map<String, Object> searchMap, int page, int size) {
        PageHelper.startPage(page,size);
        Example example = createExample(searchMap);
        Page<Order> orders = (Page<Order>) orderMapper.selectByExample(example);
        return new PageResult<Order>(orders.getTotal(),orders.getResult());
    }

    /**
     * 根据Id查询
     * @param id
     * @return
     */
    public Order findById(String id) {
        return orderMapper.selectByPrimaryKey(id);
    }

    /**
     * 新增
     * @param order
     */
    public void add(Order order) {
        orderMapper.insert(order);
    }

    /**
     * 修改
     * @param order
     */
    public void update(Order order) {
        orderMapper.updateByPrimaryKeySelective(order);
    }

    /**
     *  删除
     * @param id
     */
    public void delete(String id) {
        orderMapper.deleteByPrimaryKey(id);
    }




    /**
     * 构建查询条件
     * @param searchMap
     * @return
     */
    private Example createExample(Map<String, Object> searchMap){
        Example example=new Example(Order.class);
        Example.Criteria criteria = example.createCriteria();
        if(searchMap!=null){
            // 订单id
            if(searchMap.get("id")!=null && !"".equals(searchMap.get("id"))){
                criteria.andLike("id","%"+searchMap.get("id")+"%");
            }
            // 支付类型，1、在线支付、0 货到付款
            if(searchMap.get("payType")!=null && !"".equals(searchMap.get("payType"))){
                criteria.andLike("payType","%"+searchMap.get("payType")+"%");
            }
            // 物流名称
            if(searchMap.get("shippingName")!=null && !"".equals(searchMap.get("shippingName"))){
                criteria.andLike("shippingName","%"+searchMap.get("shippingName")+"%");
            }
            // 物流单号
            if(searchMap.get("shippingCode")!=null && !"".equals(searchMap.get("shippingCode"))){
                criteria.andLike("shippingCode","%"+searchMap.get("shippingCode")+"%");
            }
            // 用户名称
            if(searchMap.get("username")!=null && !"".equals(searchMap.get("username"))){
                criteria.andLike("username","%"+searchMap.get("username")+"%");
            }
            // 买家留言
            if(searchMap.get("buyerMessage")!=null && !"".equals(searchMap.get("buyerMessage"))){
                criteria.andLike("buyerMessage","%"+searchMap.get("buyerMessage")+"%");
            }
            // 是否评价
            if(searchMap.get("buyerRate")!=null && !"".equals(searchMap.get("buyerRate"))){
                criteria.andLike("buyerRate","%"+searchMap.get("buyerRate")+"%");
            }
            // 收货人
            if(searchMap.get("receiverContact")!=null && !"".equals(searchMap.get("receiverContact"))){
                criteria.andLike("receiverContact","%"+searchMap.get("receiverContact")+"%");
            }
            // 收货人手机
            if(searchMap.get("receiverMobile")!=null && !"".equals(searchMap.get("receiverMobile"))){
                criteria.andLike("receiverMobile","%"+searchMap.get("receiverMobile")+"%");
            }
            // 收货人地址
            if(searchMap.get("receiverAddress")!=null && !"".equals(searchMap.get("receiverAddress"))){
                criteria.andLike("receiverAddress","%"+searchMap.get("receiverAddress")+"%");
            }
            // 订单来源：1:web，2：app，3：微信公众号，4：微信小程序  5 H5手机页面
            if(searchMap.get("sourceType")!=null && !"".equals(searchMap.get("sourceType"))){
                criteria.andLike("sourceType","%"+searchMap.get("sourceType")+"%");
            }
            // 交易流水号
            if(searchMap.get("transactionId")!=null && !"".equals(searchMap.get("transactionId"))){
                criteria.andLike("transactionId","%"+searchMap.get("transactionId")+"%");
            }
            // 订单状态
            if(searchMap.get("orderStatus")!=null && !"".equals(searchMap.get("orderStatus"))){
                criteria.andLike("orderStatus","%"+searchMap.get("orderStatus")+"%");
            }
            // 支付状态
            if(searchMap.get("payStatus")!=null && !"".equals(searchMap.get("payStatus"))){
                criteria.andLike("payStatus","%"+searchMap.get("payStatus")+"%");
            }
            // 发货状态
            if(searchMap.get("consignStatus")!=null && !"".equals(searchMap.get("consignStatus"))){
                criteria.andLike("consignStatus","%"+searchMap.get("consignStatus")+"%");
            }
            // 是否删除
            if(searchMap.get("isDelete")!=null && !"".equals(searchMap.get("isDelete"))){
                criteria.andLike("isDelete","%"+searchMap.get("isDelete")+"%");
            }

            // 数量合计
            if(searchMap.get("totalNum")!=null ){
                criteria.andEqualTo("totalNum",searchMap.get("totalNum"));
            }
            // 金额合计
            if(searchMap.get("totalMoney")!=null ){
                criteria.andEqualTo("totalMoney",searchMap.get("totalMoney"));
            }
            // 优惠金额
            if(searchMap.get("preMoney")!=null ){
                criteria.andEqualTo("preMoney",searchMap.get("preMoney"));
            }
            // 邮费
            if(searchMap.get("postFee")!=null ){
                criteria.andEqualTo("postFee",searchMap.get("postFee"));
            }
            // 实付金额
            if(searchMap.get("payMoney")!=null ){
                criteria.andEqualTo("payMoney",searchMap.get("payMoney"));
            }

        }
        return example;
    }

}
